package com.itheima.qiniu;

import com.alibaba.fastjson2.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.UUID;

@Slf4j
public class QiniuKodoUtlis {
    private QiniuKodoConfig qiniuKodoConfig;
    public QiniuKodoUtlis(QiniuKodoConfig qiniuKodoConfig){
        this.qiniuKodoConfig=qiniuKodoConfig;
    }

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = "U6byqyDDyDIsdj9M1leqPk3g1UXRR5JL3rjCSUdo";
    private static String SECRET_KEY = "95zg2ySqslEWVQvVDut708kEN5cMuH0ZQA-eVwd3";

    // 要上传的空间（创建空间的名称）
    private static String bucketname = "java65-zpf";

    // 密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    private static Configuration cfg = new Configuration(Zone.zone1());
    // ...其他参数参考类注释
    private static UploadManager uploadManager = new UploadManager(cfg);

    // 使用的是测试域名
    private static String QINIU_IMAGE_DOMAIN = "";//TODO 外链域名
    private static final Logger logger = LoggerFactory.getLogger(QiniuKodoUtlis.class);

    public static String upload(byte[] content, String fileExt) throws IOException {
        try {

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(content, fileName, auth.uploadToken(bucketname));
            // 打印返回的信息


            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                logger.info("res.body:{}", res.bodyString());
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}
